package com.relax.pool;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class PoolDemo {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor.DiscardPolicy abortPolicy = new ThreadPoolExecutor.DiscardPolicy();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 5, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1), Executors.defaultThreadFactory(),abortPolicy);
        boolean b = pool.allowsCoreThreadTimeOut();
        System.out.println("b==" +b);
//        pool.allowCoreThreadTimeOut(true);  // 是否允许核心线程数销毁

//        pool.prestartCoreThread(); //todo  会开启一个核心线程
//        pool.prestartAllCoreThreads();//todo  会开启所有核心线程


        long curent = System.currentTimeMillis();

        for (int i = 1; i <= 0; i++) {

            pool.execute( () ->{
                System.out.println(System.currentTimeMillis() +"线程"+Thread.currentThread().getName()+"开始执行");
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            });
            int corePoolSize = pool.getCorePoolSize();
            int activeCount = pool.getActiveCount();
            long taskCount = pool.getTaskCount();
            System.out.println("提交第"+i+"个任务");
            System.out.println("线程池:corePoolSize:"+corePoolSize+",activeCount:"+activeCount+",taskCount:"+taskCount);
        }


        System.out.println("开始测试submit任务");

        List<Future<String>> retuls = new ArrayList<>();


        Future<String> submit = pool.submit(() -> {
            System.out.println(System.currentTimeMillis() + "线程" + Thread.currentThread().getName() + "开始执行");
            Thread.sleep(30000);
            return Thread.currentThread().getName();

        });

        Thread.sleep(1000);

        new Thread(()->{
            getResult(submit);
        }).start();


        new Thread(()->{
            getResult(submit);
        }).start();



//        pool.shutdown();








    }

    private static void getResult(Future<String> submit) {
        try {
            boolean done = submit.isDone();
            boolean cancelled = submit.isCancelled();
            System.out.println("线程池查询开始");
            String value = submit.get();
            System.out.println("线程池返回的结果是"+value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
